package it.okkam.longwell.ui.command;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.velocity.VelocityContext;

import sun.security.action.GetLongAction;

import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.tdb.TDBFactory;
import com.hp.hpl.jena.util.FileManager;

import edu.mit.simile.longwell.LongwellServer;
import edu.mit.simile.longwell.LongwellServlet;
import edu.mit.simile.longwell.ui.FlairMessage;
import edu.mit.simile.longwell.ui.InjectionManager;
import edu.mit.simile.longwell.ui.command.CommandBase;

public class AdministrationAccessesCommand extends CommandBase {
	final static private Logger s_logger = Logger
			.getLogger(AdministrationCommand.class);
	protected ServletContext context;
	public static boolean userInput = false;
	final protected String m_template;
	HashMap<String, String> userForSession = new HashMap<String, String>();

	public AdministrationAccessesCommand(InjectionManager injectionManager,
			String template) {
		super(injectionManager);
		m_template = template;
	}

	public void execute(FlairMessage msg) throws ServletException {
		try {
			VelocityContext vcContext = createContext(msg);
			HttpSession session = msg.m_request.getSession();
			String sessionId = msg.m_request.getSession().getId();
			String username = msg.getProfile(sessionId).getUserName();
			context = msg.m_servlet.getServletContext();
			String fileName = LongwellServer.getUsersDatasetPath(); 
			vcContext.put("timeLogins", getTimeLogins(msg));		
			msg.m_ve.mergeTemplate("templates/commands/administration_accesses.vt",
					vcContext, msg.m_response.getWriter());
			//}
		} catch (Exception e) {
			s_logger.error(e);
			e.printStackTrace();
		}

	}

	//metodo che restituisce una lista con tutti i login effettuati dall'utente con relativa data/ora
	protected List getTimeLogins(FlairMessage msg) {
		//Model model = LongwellServer.getBCCDataset().getDefaultModel();
		Model model = LongwellServer.getBCCDataset().getNamedModel("http://www.provincia.tn.it/bcc/resource/bcc-utenti");
		String loginQuery =

		"PREFIX dul: <http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#> "
		+ "PREFIX foaf: <http://xmlns.com/foaf/0.1/> "
		+ "PREFIX bcc: <http://www.provincia.tn.it/ont/bcc.owl#> "
		+ " SELECT ?date ?participant "  
		+ " WHERE { "
		+ " ?event a bcc:UserLogin . "
		+ " ?event dul:hasEventDate ?date . "
		+ " ?event dul:hasParticipant ?participant . "
		//+ " ?participant foaf:nickname ?nickname . "
		+ "} order by ?date";

		Query query = QueryFactory.create(loginQuery);

		QueryExecution qe = QueryExecutionFactory.create(query, model);
		ResultSet results = qe.execSelect();

		Set actions = new HashSet<String>();
		while (results.hasNext()) {
			QuerySolution login = results.next();
			String date = login.get("date").toString().substring(0,19).replace("T", " ");
			String participant = login.get("participant").toString();
			s_logger.info(date +" "+participant);
			actions.add("Login"+date+"|"+participant);
		}
		qe.close();
		
		String logoutQuery =

		"PREFIX dul: <http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#> "
		+ "PREFIX foaf: <http://xmlns.com/foaf/0.1/> "
		+ "PREFIX bcc: <http://www.provincia.tn.it/ont/bcc.owl#> "
		+ " SELECT ?date ?participant "  
		+ " WHERE { "
		+ " ?event a bcc:UserLogout . "
		+ " ?event dul:hasEventDate ?date . "
		+ " ?event dul:hasParticipant ?participant . "
		//+ " ?participant foaf:nickname ?nickname . "
		+ "} order by ?date";

		Query queryLogout = QueryFactory.create(logoutQuery);

		QueryExecution qeLogout = QueryExecutionFactory.create(queryLogout, model);
		ResultSet resultsLogout = qeLogout.execSelect();

		while (resultsLogout.hasNext()) {
			QuerySolution logout = resultsLogout.next();
			String date = logout.get("date").toString().substring(0,19).replace("T", " ");
			String participant = logout.get("participant").toString();
			s_logger.info("Logout "+date +" "+participant);
			actions.add(date+"|"+participant);
		}
		qeLogout.close();
		
		
		List<String> sortedList = new ArrayList<String>(actions);
		Comparator<String> comparator = Collections.reverseOrder();
		Collections.sort(sortedList,comparator);
		return sortedList;
	}
}
